package com.example.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.store.common.BaseContext;
import com.example.store.common.IDUtils;
import com.example.store.common.IpUtil;
import com.example.store.common.Result;
import com.example.store.entity.Cart;
import com.example.store.entity.Goods;
import com.example.store.entity.Record;
import com.example.store.entity.Time;
import com.example.store.service.GoodsService;
import com.example.store.service.RecordService;
import com.example.store.service.TimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/goods")
public class GoodsController {//商品相关操作

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private TimeService timeService;

//    生成日志
    private void makeTime(String id, HttpServletRequest request, String operate){
        Time time = Time.createTime(id, 4);
        String ip = IpUtil.getIp(request);
        time.setIp(ip);
        time.setOperate(operate);
        timeService.save(time);
    }

//    图片存储路径
    private final String filePath="storePhoto";

//    分页大小
    private final Integer pageSize = 10;

//    新增商品
    @PostMapping("/newGoods")
    public Result<String> newGoods(@RequestBody Goods goods, HttpServletRequest request){

//        用户、合法性校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||(userId.charAt(0)!='s')){
            return Result.error("请销售员登录");
        }
        if(!(StringUtils.hasText(goods.getName())&&StringUtils.hasText(goods.getIntro())&&goods.getPrice()!=null)){
         return Result.error("请填写完整信息");
        }
        if(goods.getCount()<0){
            return Result.error("库存不能小于0");
        }
        if(goods.getPrice()<=0){
            return Result.error("价格不能小于0");
        }
        goods.setSeller(userId);
        goods.setId(IDUtils.getId());
        goods.setSold(0L);
        goodsService.save(goods);

//        操作日志
        makeTime(userId, request, "添加商品:"+goods.getId());

//        返回goods的id
        return Result.success(goods.getId());
    }

//    上传图片
    @PostMapping("/upLoadPhoto")
    public Result<String> upLoadPhoto(@RequestParam("file") MultipartFile file,
                                      @RequestParam("id") String goodsId, HttpServletRequest request){

//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||userId.charAt(0)!='s'&&!userId.equals("root")){
            return Result.error("请销售员登录");
        }
        if(goodsId==null){
            return Result.error("未选择商品");
        }
        Goods goods = goodsService.getById(goodsId);
        if(goods==null){
            return Result.error("未选择商品");
        }
        if(!userId.equals("root")&&!goods.getSeller().equals(userId)){
            return Result.error("无权操作");
        }
        if(file==null){
            return Result.error("未选择图片");
        }

//        保存图片到本地
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String photo = IDUtils.getId();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath +"/"+ photo);
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件保存失败");
        }

//        将图片的文件名存入数据库
        Goods goods1 = new Goods();
        goods1.setId(goodsId);
        goods1.setPhoto(photo);
        goodsService.updateById(goods1);

//        操作日志
        makeTime(userId, request, "更新商品图片:"+goodsId);

        return Result.success(photo);
    }

    //给销售人员或者管理者提供分页
    @PostMapping("/page")
    public Result<Page<Goods>> page(@RequestBody Map<String, String> pageNum, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||userId.charAt(0)!='s'&&!userId.equals("root")){
            return Result.error("请销售员登录");
        }

        if(pageNum.get("pageNum")==null){
            return Result.error("无效页码");
        }
        Page<Goods> pageInfo = new Page<>(Integer.parseInt(pageNum.get("pageNum")), pageSize);
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();

        if(!userId.equals("root")){//销售人员则id为userId（查自己），管理员通过前端传入
            queryWrapper.eq(Goods::getSeller, userId);
        }
        else{
            queryWrapper.eq(Goods::getSeller, pageNum.get("seller"));
        }

        //依照库存排序
        queryWrapper.orderByDesc(Goods::getCount);
        goodsService.page(pageInfo, queryWrapper);

//        记录日志
        makeTime(userId, request, "商品分页");

        return Result.success(pageInfo);
    }

//    给顾客分页（商品列表）
    @PostMapping("/pageForUser")
    public Result<Page<Goods>> pageForUser(@RequestBody Map<String, String> pageNum, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||(userId.charAt(0)!='u'&&!userId.equals("guest"))){
            return Result.error("请登录");
        }

        if(pageNum.get("pageNum")==null){
            return Result.error("无效页码");
        }

//      只显示在售的（库存不为负数）
        String seller = pageNum.get("seller");
        Page<Goods> pageInfo = new Page<>(Integer.parseInt(pageNum.get("pageNum")), pageSize);
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getSeller, seller);
        queryWrapper.ge(Goods::getCount, 0);
        //依照库存排序
        queryWrapper.orderByDesc(Goods::getCount);
        goodsService.page(pageInfo, queryWrapper);

//        记录日志
        makeTime(userId, request, "商品分页");

        return Result.success(pageInfo);
    }


//    更新商品文字信息
    @PostMapping("/update")
    public Result<String> update(@RequestBody Goods goods, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||userId.charAt(0)!='s'&&!userId.equals("root")){
            return Result.error("请销售员登录");
        }
        if(goods==null){
            return Result.error("无商品");
        }
        if(goodsService.getById(goods.getId())==null){
            return Result.error("无商品");
        }
        if(!userId.equals("root")&&!goodsService.getById(goods.getId()).getSeller().equals(userId)){
            return Result.error("无权操作");
        }

        if(!(StringUtils.hasText(goods.getName())&&StringUtils.hasText(goods.getIntro())&&goods.getPrice()!=null)){
            return Result.error("请填写完整信息");
        }
        if(goods.getCount()<0){
            goods.setCount(-1L);
        }
        if(goods.getPrice()<=0){
            return Result.error("价格不能小于0");
        }
        goodsService.updateById(goods);

//        记录日志
        makeTime(userId, request, "更新商品信息:"+goods.getId());

        return Result.success("修改成功");
    }

//    下架商品，将库存设置为-1
    @PostMapping("/down")
    public Result<String> down(@RequestBody Goods goods, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||(userId.charAt(0)!='s'&&!userId.equals("root"))){
            return Result.error("请销售员登录");
        }
        if(goods==null){
            return Result.error("无商品");
        }
        Goods goods1 = goodsService.getById(goods.getId());
        if(goods1==null){
            return Result.error("无商品");
        }

        if(!userId.equals("root")&&!goods1.getSeller().equals(userId)){
            return Result.error("无权操作");
        }

        goods1.setCount(-1L);
        goodsService.updateById(goods1);

//        记录日志
        makeTime(userId, request, "下架商品:"+goods1.getId());

        return Result.success("已下架"+goods1.getName());
    }


//    查看商品详情
    @PostMapping("/details")
    public Result<Goods> details(@RequestBody Goods goods, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||(userId.charAt(0)!='u'&&!userId.equals("guest")&&userId.charAt(0)!='s'&&!userId.equals("root"))){
            return Result.error("请登录");
        }
        if(goods==null||goods.getId()==null){
            return Result.error("无商品");
        }
        Goods goods1 = goodsService.getById(goods.getId());

//        记录日志
        makeTime(userId, request, "查看商品详情:"+goods.getId());

        return Result.success(goods1);
    }

//    浏览记录（记录页面停留时间，前端返回）
    @PostMapping("/record")
    public void record(@RequestBody Record record){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||(userId.charAt(0)!='u'&&!userId.equals("guest"))){
            return;
        }
        if(record==null||record.getTime()==null||record.getTime()<=0){
            return;
        }

//        保存记录
        record.setType(0);
        record.setUserid(userId);
        record.setDate(LocalDateTime.now());
        recordService.save(record);
    }

    //用户浏览、购买、停留时间查看
    @PostMapping("/recordPage")
    public Result<Page<Record>> recordPage(@RequestBody Map<String, String> pageNum, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||(userId.charAt(0)!='s'&&!userId.equals("root"))){
            return Result.error("请销售员登录");
        }

        if(pageNum.get("pageNum")==null){
            return Result.error("无效页码");
        }
        if(pageNum.get("goodsid")==null){
            return Result.error("无商品");
        }
        Goods goods = goodsService.getById(pageNum.get("goodsid"));
        if(goods==null){
            return Result.error("无商品");
        }
        if(!goods.getSeller().equals(userId)&&!userId.equals("root")){
            return Result.error("不是你的商品");
        }

//        0为浏览记录，1为购买记录
        Integer type = Integer.parseInt(pageNum.get("type"));
        if(type!=0&&type!=1){
            return Result.error("错误的类型");
        }
        Page<Record> pageInfo = new Page<>(Integer.parseInt(pageNum.get("pageNum")), pageSize);
        LambdaQueryWrapper<Record> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Record::getGoodsid, pageNum.get("goodsid"));
        queryWrapper.eq(Record::getType, type);
        queryWrapper.orderByDesc(Record::getDate);
        recordService.page(pageInfo, queryWrapper);

//        记录日志
        makeTime(userId, request, "查看商品购买与浏览记录:"+pageNum.get("goodsid"));

        return Result.success(pageInfo);
    }

//    统计年购买及浏览记录
    @PostMapping("/sumTime")
    public Result<List<Record>> sumTime(@RequestBody Record record, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||(userId.charAt(0)!='s'&&!userId.equals("root"))){
            return Result.error("请销售员登录");
        }
        if(record==null||record.getGoodsid()==null){
            return Result.error("无商品");
        }
        Goods goods1 = goodsService.getById(record.getGoodsid());
        if(goods1==null){
            return Result.error("无商品");
        }
        if(!goods1.getSeller().equals(userId)&&!userId.equals("root")){
            return Result.error("不是你的商品");
        }

//        sumList为十二个月的统计值，用record类存储，count为销售量，time为浏览时间
        List<Record> sumList = new ArrayList<>();

        LambdaQueryWrapper<Record> queryWrapper = null;
        LocalDateTime now = record.getDate();

        //获取每个月的记录
        for(int i=0;i<12;i++){
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Record::getGoodsid, record.getGoodsid());
            queryWrapper.ge(Record::getDate, now);
            now = now.plusMonths(1L);
            queryWrapper.lt(Record::getDate, now);
            List<Record> records = recordService.list(queryWrapper);
            Record sum = new Record();
            sum.setCount(0L);
            sum.setTime(0L);
            for (Record value : records) {
                sum.setCount(sum.getCount()+value.getCount());
                sum.setTime(sum.getTime()+value.getTime());
            }
            sumList.add(sum);
        }

//        记录日志
        makeTime(userId, request, "查看商品统计信息:"+record.getGoodsid());

        return Result.success(sumList);
    }

    //    用于管理员查询
    @PostMapping("/search")
    public Result<Goods> search(@RequestBody Goods goods){
        //        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||!userId.equals("root")){
            return Result.error("请管理员登录");
        }

        Goods goods1 = goodsService.getById(goods.getId());
        if(goods1==null){
            return Result.error("无");
        }
        return Result.success(goods1);
    }
}
